<template>
  <el-form
    ref="form"
    :label-position="labelPosition"
    :label-width="labelWidth"
    :model="form"
    :rules="rules"
    class="bold-label"
  >
    <el-form-item label="性别" ref="gender" prop="gender">
      <el-radio-group v-show="editing" v-model="form.gender">
        <el-radio :label="1">男</el-radio>
        <el-radio :label="0">女</el-radio>
      </el-radio-group>
      <div v-show="!editing">
        {{ genderDisplay }}
        <field-modify-button v-model="editing" />
      </div>
    </el-form-item>
    <el-form-item v-show="editing">
      <field-submit-buttons :loading="loading" @submit="updateInfo" @cancel="cancel" />
    </el-form-item>
  </el-form>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import { formatUser } from '@/views/users/format';
import FieldModifyButton from '@/views/users/edit/components/field-modify-button';
import FieldSubmitButtons from '@/views/users/edit/components/field-submit-buttons';

export default {
  name: 'form-gender',
  components: { FieldModifyButton, FieldSubmitButtons },
  props: {
    labelPosition: { // top left right
      type: String,
      default: 'left',
    },
    labelWidth: {
      type: String,
      default: '140px',
    },
  },
  data() {
    return {
      form: {
        gender: 1,
      },
      rules: {
        gender: [{ validator: this.$va.gender }],
      },
      loading: false,
      editing: false,
    };
  },
  computed: {
    ...mapState({ curUser: 'currentUser' }),
    // 更新用户信息所需参数
    updateInfoParams() {
      return {
        userId: this.curUser.id,
        gender: this.form.gender,
      };
    },
    genderDisplay() {
      switch (this.form.gender) {
        case 1: return '男';
        case 0: return '女';
        default: return '';
      }
    },
  },
  created() {
    this.resetForm();
  },
  methods: {
    ...mapActions({ setCurUser: 'setCurrentUser' }),
    // 更新用户信息
    updateInfo() {
      this.$refs.form.validate((valid, errs) => {
        if (valid) {
          this.loading = true;
          this.$api.users.update(this.updateInfoParams)
            .then((res) => {
              this.$message.success('修改成功');
              this.setCurUser(Object.assign(formatUser(res.data), { token: this.curUser.token }));
              this.editing = false;
            })
            .catch(() => {})
            .then(() => { this.loading = false; });
        } else this.$refs[Object.keys(errs)[0]].$el.scrollIntoView({ block: 'center' });
      });
    },
    // 取消更新
    cancel() {
      this.resetForm();
      this.editing = false;
    },
    // 重置用户信息
    resetForm() {
      let genderNum;
      if (this.curUser.gender === 'female') genderNum = 0;
      else if (this.curUser.gender === 'male') genderNum = 1;
      this.$set(this.form, 'gender', genderNum);
    },
  },
};
</script>

<style></style>
